package com.ffcs.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

import com.ffcs.constants.FfcsConstants;
import com.ffcs.model.RandomAccessToken;
import com.smart.util.WeixinUtil;

import net.sf.json.JSONObject;

//获取令牌接口
public class RandomAccessTokenManager {
  private static RandomAccessToken accessToken;
  private static long getTime;
  public static boolean isExpired()
  {
	  Date d=new Date();
	  //计算当前到现在经过了多少秒
	  long interval=(d.getTime()-getTime)/1000;
	  if(interval>accessToken.getExpires_in()-3) //之所以减去3秒，是考虑程序等会执行时AccessToken可能会过期
             return true;
	  else return false;
  }
  public static String getRandomAccessToken()
  {
	  System.out.println("开始获取RandomAccessToken");
	  if(accessToken==null||isExpired())
	  {
		  System.out.println("accessToken is null or expired");
		  //如果AccessToken为空，则必须先初始化AccessToken
		  if(accessToken==null) accessToken=new RandomAccessToken();
		  String url=FfcsConstants.ACCESS_TOKEN_URL;
		  String postEntity="grant_type=client_credentials&"+"app_id="+FfcsConstants.APPID+"&app_secret="+FfcsConstants.APPSECRET;
		  System.out.println("url:"+url);
		  System.out.println("postEntity:"+postEntity);
		  try 
		  {
		    JSONObject jsonObject = WeixinUtil.doPostStr2(url, postEntity);
		    String resMessage=jsonObject.getString("res_message");
		    String resCode=jsonObject.getString("res_code");
		    if(resMessage.equals("Success"))
		    {
			  System.out.println("获取accessToken成功");
			  System.out.println(jsonObject);
			  accessToken.setAccessToken(jsonObject.getString("access_token"));
			  accessToken.setExpires_in(jsonObject.getInt("expires_in"));
			  getTime=new Date().getTime();
		    }
		    else
		    {
			  System.out.println("获取RandomAccessToken失败，错误码为："+resCode);
		    }
		  } catch (IOException e) {
				e.printStackTrace();
			}
	  }
	  else System.out.println("accessToken not need to get");
	  return accessToken.getAccessToken();
  }
  
  public static void main(String[] args)
  {
			System.out.println(RandomAccessTokenManager.getRandomAccessToken());
  }
}
